#include <iostream>
using std::cout;
using std::endl;


//理解operator new函数和operator delete函数
//理解定位new
class MyClass
{
public:
	MyClass(int _a = 0)
		:a(_a)
	{
		cout << "MyClass()" << endl;
	}
	~MyClass()
	{
		cout << "~MyClass()" << endl;
	}
	void printValue()
	{
		cout << "a is：" << a << endl;
	}
private:
	int a;
};

int main()
{
    // int a = 2;
	// int b = 3;
	// void* ptr = &a; //正确。可以使用void*类型指针变量接收任何类型的指针
	// void* ptr1 = malloc(3);
	// //int* ptr2 = ptr1; //错误。必须将ptr1强转成int*才可以被ptr2接收
	// void* new_ptr = malloc(9);
	// *((void**)new_ptr) = &a; //new_ptr指针指向内存中前4/8个字节的数据的类型是void*
	// *((void**)new_ptr + 1) = &b;
	// int* ptr_a = (int*)(*((void**)new_ptr));
	// int* ptr_b = (int*)(*((void**)new_ptr + 1));
	// cout << *ptr_a << " " << *ptr_b;

	void* ptr = operator new(sizeof(MyClass)); //调用operator new在堆上创建内存
	MyClass* myclass_ptr = new(ptr)MyClass(9); //使用定位new在分配的内存上构造对象
	myclass_ptr->printValue();
	myclass_ptr->~MyClass();
	operator delete(ptr); //释放使用operator new函数分配的空间

	void* ptr1 = operator new(6);
	int* a_ptr = new(ptr1)int(2);
	cout << *a_ptr << endl; //结果是2
	cout << ptr1 << " " << a_ptr << endl;
	operator delete(a_ptr);
	return 0;
}